import React, { useState, useEffect } from 'react';
import { View, Text, Navigator } from '@tarojs/components';
import * as echarts from '../../ec-canvas/echarts';
import { Checklist, Message, Download } from '@nutui/icons-react-taro';
import { dashboardApi } from '../../services/dashboardApi';

// 图表初始化函数 - 组长仪表盘专用
function initChart(canvas, width, height, deptData) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(chart);

  // 默认数据
  const defaultData = {
    days: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    avgScores: [68, 72, 76, 74, 75, 72, 76],
    maxScores: [85, 90, 92, 88, 95, 89, 91],
    minScores: [45, 47, 50, 52, 48, 42, 45]
  };

  // 使用API返回的数据（如果有）
  const chartData = deptData?.stats_by_day ? {
    days: deptData.stats_by_day.map(item => item.day),
    avgScores: deptData.stats_by_day.map(item => item.avg_score),
    maxScores: deptData.stats_by_day.map(item => item.max_score),
    minScores: deptData.stats_by_day.map(item => item.min_score)
  } : defaultData;

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['平均完成率', '最高完成率', '最低完成率'],
      center: 0,
      top: 0,
      textStyle: {
        fontSize: 10
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: chartData.days
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value} %'
      }
    },
    series: [
      {
        name: '平均完成率',
        type: 'line',
        data: chartData.avgScores,
        itemStyle: {
          color: '#3b82f6'
        },
        smooth: true
      },
      {
        name: '最高完成率',
        type: 'line',
        data: chartData.maxScores,
        itemStyle: {
          color: '#10b981'
        },
        smooth: true
      },
      {
        name: '最低完成率',
        type: 'line',
        data: chartData.minScores,
        itemStyle: {
          color: '#f59e0b'
        },
        smooth: true
      }
    ]
  };

  chart.setOption(option);
  return chart;
}

const LeaderDashboard = () => {
  const [departmentData, setDepartmentData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchDepartmentData = async () => {
      try {
        const res = await dashboardApi.getDepartmentReport();
        if (res) {
          setDepartmentData(res);
        }
      } catch (error) {
        console.error('获取部门报告失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchDepartmentData();
  }, []);

  const ec = {
    onInit: (canvas, width, height) => initChart(canvas, width, height, departmentData)
  };

  // 风险学生列表 - 默认展示未提交日报的学生
  const riskStudents = departmentData?.missing_members || [
    { id: "2021001", name: "张立" },
    { id: "2021002", name: "王洋" },
    { id: "2021003", name: "刘畅" }
  ];

  return (
    <View className="leader-dashboard">
      <View className="task-card">
        <View className="card-header">
          <Text className="card-title">小组整体概览</Text>
          <Text className="card-action">查看详情</Text>
        </View>

        <View className="stats-container">
          <View className="stat-card">
            <Text className="stat-label">组员人数</Text>
            <View className="stat-value-container">
              <Text className="stat-value">{departmentData?.member_count}</Text>
            </View>
          </View>
          <View className="stat-card">
            <Text className="stat-label">平均完成率</Text>
            <View className="stat-value-container">
              <Text className="stat-value">{departmentData?.today_avg_score}%</Text>
              <Text className="stat-change warning">↑</Text>
            </View>
          </View>
          <View className="stat-card">
            <Text className="stat-label">待处理预警</Text>
            <View className="stat-value-container">
              <Text className="stat-value" style={{ color: '#ef4444' }}>{departmentData?.missing_report_count}</Text>
            </View>
          </View>
        </View>
      </View>

      <View className="chart-card">
        <View className="chart-header">
          <Text className="chart-title">组员学习进度趋势</Text>
          <View className="tab-group">
            <Text className="tab active">周</Text>
            <Text className="tab inactive">月</Text>
          </View>
        </View>

        <View className="chart-container">
          <ec-canvas force-use-old-canvas="true" id="leaderProgressChartDom" canvas-id="leaderProgressChart" ec={ec}></ec-canvas>
        </View>
      </View>

      <View className="risk-student-card">
        <View className="risk-header">
          <View className="header-content">
            <Text className="header-title">需要关注的学生</Text>
            <Text className="header-action">查看全部</Text>
          </View>
        </View>

        {riskStudents.map((student, index) => (
          <View className="risk-item" key={student.id || index}>
            <View className="avatar high-risk">
              <Text className="avatar-text">{student.name.slice(-2)}</Text>
            </View>
            <View className="student-content">
              <Text className="student-name">{student.name}</Text>
              <Text className="student-detail">
                未提交昨日学习日报
              </Text>
            </View>
            <View className="status-container">
              <View className="risk-badge high-risk">
                <View className="status-dot high-risk"></View>
                <Text>高风险</Text>
              </View>
            </View>
          </View>
        ))}

        {riskStudents.length === 0 && (
          <View className="empty-risk">
            <Text>暂无需要关注的学生</Text>
          </View>
        )}
      </View>

      {/* <View className="quick-actions-card">
        <Text className="section-title">快速操作</Text>

        <View className="actions-grid">
          <Navigator url="/pages/task/assign" className="action-item blue">
            <View className="action-icon-wrapper blue">
              <Checklist size="20" color="#3b82f6" />
            </View>
            <Text className="action-name">任务发布</Text>
          </Navigator>

          <Navigator url="/pages/notification/send" className="action-item green">
            <View className="action-icon-wrapper green">
              <Message size="20" color="#10b981" />
            </View>
            <Text className="action-name">发送通知</Text>
          </Navigator>

          <Navigator url="/pages/report/export" className="action-item purple">
            <View className="action-icon-wrapper purple">
              <Download size="20" color="#8b5cf6" />
            </View>
            <Text className="action-name">导出报告</Text>
          </Navigator>
        </View>
      </View> */}
    </View>
  );
};

export default LeaderDashboard;
